package com.wonders.common.exception.handler;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import org.slf4j.Logger;

import com.wonders.framework.exception.BusinessException;
import com.wonders.framework.util.DateUtil;
import com.wonders.framework.util.JsonUtil;
import com.wonders.framework.util.web.DeviceUtil;
import com.wonders.framework.util.web.RequestUtil;

/**
 * 异常处理
 * 
 * @author WuBin
 * 
 */
public class ExceptionHandler extends SimpleMappingExceptionResolver implements
		HandlerExceptionResolver {

	private Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String tipMsg = null;
		// 当是业务异常时，直接提示异常信息，否则当作系统异常统一处理
		if (ex instanceof BusinessException) {
			tipMsg = ex.getMessage();
		} else {
			StringBuffer exceptionId = new StringBuffer(DateUtil.toChar())
					.append("_")
					.append(request.getLocalAddr().replace(".", ""))
					.append(request.getLocalPort()).append("_")
					.append(RandomStringUtils.randomAlphabetic(5));
			logger.error("系统运行异常,异常编号:{},请求地址:{},请求参数:{},操作系统:{},浏览器内核:{}",
					exceptionId, request.getRequestURI(),
					JsonUtil.toJson(request.getParameterMap()),
					DeviceUtil.getOS(), DeviceUtil.getBrowser(), ex);
			tipMsg = "系统运行异常,异常编号:" + exceptionId;
		}
		// 区分请求类型，分别响应
		if (RequestUtil.isAjaxRequest()) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("success", false);
			map.put("type", "tip");
			map.put("msg", tipMsg);
			RequestUtil.ajaxResponse(JsonUtil.toJson(map));
			return null;
		} else {
			return new ModelAndView("global/error").addObject("msg", tipMsg);
		}
	}

}
